import { isArrayEmpty } from "@/utils";
import { useAppStore } from "@/store/modules/app";
const appStore = useAppStore();

const handlePerms = (permissions: string[], value: string[], el: any) => {
  const all_permission = "*:*:*";
  const permissionFlag = value;
  const hasPermissions = permissions.some(permission => {
    return all_permission === permission || permissionFlag.includes(permission)
  })
  if (!hasPermissions) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

export default {
  mounted(el: Element, binding: any) {
    const { value } = binding
    const permissions = appStore.getPermissionBtns
    if (isArrayEmpty(value)) {
      throw new Error(`请设置操作权限标签值`);
    }
    if (isArrayEmpty(permissions)) {
      setTimeout(() => {
        let newPermissions = appStore.getPermissionBtns;
        handlePerms(newPermissions, value, el);
      }, 100);
    } else {
      handlePerms(permissions, value, el);
    }
  }
}